/*
 * @Author: c
 * @Date: 2024-01-04 18:11:33
 * @LastEditTime: 2024-01-05 18:18:23
 * @LastEditors: c
 * @Description: 
 * @FilePath: \music-web-backend\src\common\service\excel.service.ts
 * https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// Copyright 2024 Administrator
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { Injectable } from "@nestjs/common";
import { Workbook } from 'exceljs'
import { ExportExcelDto } from "../dto/excel.dto";
import { Response } from "express";

export class ExcelService<T> {
    static async export<T>(res: Response, excelExportDto: ExportExcelDto<T>) {
        const workbook = new Workbook();
        workbook.creator = excelExportDto?.creator ?? '未知用户创建'
        workbook.created = new Date()
        workbook.title = "一个excel表格数据的标题"

        const worksheet = workbook.addWorksheet('excel表格');
        worksheet.columns = excelExportDto.columns
        // 定义表头名称和字段名
        // worksheet.columns = [
        //     { header: 'ID', key: 'id', width: 42 },
        //     { header: '项目名称', key: 'name', width: 32 },
        //     { header: '所属区域', key: 'regionName' },
        //     { header: '订单编号', key: 'orderNumber' },
        //     { header: '管理单位', key: 'organization' },
        //     { header: '联系人', key: 'contact' },
        //     { header: '联系电话', key: 'phone', width: 12 },
        //     { header: '建设时间', key: 'buildAt', width: 12 },
        //     { header: '备注', key: 'remark' },
        // ];
        const result = excelExportDto.result; // result是通过前端传递的ids从数据库获取需要导出的信息
        worksheet.addRows(result);
        const buffer = await workbook.xlsx.writeBuffer(); // 前端接受到的数据格式为{type: 'buffer', data: []}
        res.set('Content-Disposition', `attachment; filename=example.xlsx`).send(buffer)
    }


    static getProjectCell(target, key, value) {
        const handler = {
            1: (target, value) => {
                target.username = value;
            },
            2: (target, value) => {
                target.nickname = value;
            },
            3: (target, value) => {
                target.gender = value;
            },
            4: (target, value) => {
                target.mobile = value;
            },
            5: (target, value) => {
                target.email = value;
            },
            6: (target, value) => {
                target.roleDesc = value;
            }
        };
        handler[key] && handler[key](target, value);
    }


    static async import(file: Express.Multer.File): Promise<any[]> {
        const { buffer } = file; // file为前端上传的excel
        const workbook = new Workbook();
        await workbook.xlsx.load(buffer); // 加载buffer文件
        const worksheet = workbook.getWorksheet(1); // 获取excel表格的第一个sheet
        const result = [];
        worksheet.eachRow((row, rowNumber) => {
            console.log('工作表' + rowNumber);
            // 第一行是表头，故从第二行获取数据
            if (rowNumber > 1) {
                const target = {};
                row.eachCell((cell, colNumber) => {
                    ExcelService.getProjectCell(target, colNumber, cell.value);
                });
                result.push(target);
            }
        });
        console.log(result); // result就是我们提取excel需要导入数据库的数据
        return result
    }
}